package com.eastandroid.zoom;

import java.util.Observable;
import java.util.Observer;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;

import com.loopj.android.image.SmartImageView;

public class ZoomView extends SmartImageView implements Observer {

	private static final String TAG = "ImageZoomView";

	private final Paint mPaint = new Paint(Paint.FILTER_BITMAP_FLAG);
	private ZoomState mZoomState;
	public void setZoomState(ZoomState zoomState) {
		mZoomState = zoomState;
	}

	protected Bitmap mBitmap;
	public void setImage(Bitmap bitmap) {
		mBitmap = bitmap;
		mZoomState.setOriginalRect(0,0,bitmap.getWidth(),bitmap.getHeight());
		mZoomState.reset();
		invalidate();
		
	}

	@Override
	public void setImageBitmap(Bitmap bm) {
		if(null == bm){
			super.setImageBitmap(null);
			return;
		}
		setImage(bm);
	}

	public ZoomView(Context context) {
		super(context);
		create(context);
	}

	public ZoomView(Context context, AttributeSet attrs) {
		super(context, attrs);
		create(context);
	}

	public ZoomView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		create(context);
	}

	private void create(Context context) {
		// Log.e(TAG, ""+"at "+new Exception().getStackTrace()[0].toString());
	}

	@Override
	protected void onDraw(Canvas canvas) {
		if (mBitmap != null && mZoomState != null) {
			canvas.save();
			canvas.concat(mZoomState.getMatrix());
			canvas.drawBitmap(mBitmap, 0, 0, mPaint);
			canvas.restore();
		}
	}

	public void update(Observable observable, Object data) {
		invalidate();
	}

	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
		mZoomState.setFrameRect(0, 0, w, h);
		super.onSizeChanged(w, h, oldw, oldh);
	}
	
}
